package com.finger.forest.ui.notice;

import android.content.Intent;
import android.os.Bundle;
import android.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.finger.forest.CheckLookVideoActivity;
import com.finger.forest.HotCheckActivity;
import com.finger.forest.NoticeEditActivity;
import com.finger.forest.R;
import com.finger.forest.ToMapLocationActivity;
import com.finger.forest.adapter.NoticeItemAdapter;
import com.finger.forest.base.BaseFragment;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.dialog.DeleteNoticeDialog;
import com.finger.forest.dialog.NoticeItemDialog;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.NoticeChooseReadingItemModel;
import com.finger.forest.model.NoticeChooseTopItemModel;
import com.finger.forest.model.NoticeItemModel;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.UniversalItemDecoration;
import com.google.gson.Gson;
import com.jakewharton.rxbinding2.view.RxView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 消息中心
 */
public class NoticeFragment extends BaseFragment<RegisterPresenter> implements BaseView {

    private Unbinder unbinder;

    /**
     * 右边按钮
     */
    @BindView(R.id.btn_right)
    ImageView btn_right;
    @BindView(R.id.rvNotice)
    RecyclerView rvNotice;

    @BindView(R.id.viewBottom)
    View viewBottom;

    @BindView(R.id.srlRefresh)
    SmartRefreshLayout srlRefresh;
    @BindView(R.id.tvReading)
    TextView tvReading;
    @BindView(R.id.tvTop)
    TextView tvTop;
    @BindView(R.id.tvNoticeDelete)
    TextView tvNoticeDelete;

    private NoticeItemAdapter noticeItemAdapter;

    /**
     * 消息列表
     */
    private List<NoticeItemModel> noticeItemModels = new ArrayList<>();

    /**
     * 已读选中
     */
    private List<NoticeItemModel> noticeChooseReadingItemModels = new ArrayList<>();

    /**
     * 置顶选中
     */
    private List<NoticeChooseTopItemModel> noticeChooseTopItemModels = new ArrayList<>();

    /**
     * 是否显示消息管理，默认false不显示
     */
    private boolean isShow = false;

    private DeleteNoticeDialog deleteNoticeDialog;
    private NoticeItemDialog noticeItemDialog;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, root);
        return root;
    }

    @Override
    protected void receiveData() {
    }

    @Override
    protected void initializeNavigation() {

    }

    @Override
    protected void initializeView() {

        noticeItemAdapter = new NoticeItemAdapter(R.layout.notice_item_view, noticeItemModels);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        rvNotice.setLayoutManager(linearLayoutManager);
        rvNotice.setAdapter(noticeItemAdapter);
        rvNotice.addItemDecoration(new UniversalItemDecoration() {
            @Override
            public Decoration getItemOffsets(int position) {
                ColorDecoration colorDecoration = new ColorDecoration();
                colorDecoration.bottom = getResources().getDimensionPixelOffset(R.dimen.dp_10);
                return colorDecoration;
            }
        });

        noticeItemAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (isShow) {
                    //编辑状态下，不可点击
                    return;
                }

                if (null == noticeItemDialog) {
                    noticeItemDialog = new NoticeItemDialog(getActivity(), R.style.dialogFullStyle, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (v.getId() == R.id.tvLook) {
                                Intent intent = new Intent(getContext(), CheckLookVideoActivity.class);
                                startActivity(intent);
                                noticeItemDialog.dismiss();
                            } else if (v.getId() == R.id.tvLocation){
                                String id = noticeItemModels.get(position).getNoticeContent();
                                Intent intentLocation = new Intent(getContext(), HotCheckActivity.class);
                                intentLocation.putExtra("hId",id);
                                context.startActivity(intentLocation);
                                noticeItemDialog.dismiss();
                            }
                        }
                    });
                }

                noticeItemDialog.show();
            }
        });

        clicks();
    }

    @Override
    protected void loadDataFromServer() {
        srlRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                loadData();

                viewBottom.setVisibility(View.GONE);
                isShow = false;
            }
        });

        srlRefresh.autoRefresh();
    }

    /**
     * 获取消息列表
     */
    private void loadData() {
        Map<String, Object> maps = new HashMap<>();
        //maps.put("UserID", userId);

        presenter.userNoticeList(maps);
    }

    /**
     * 点击事件，使用RxView，避免多次点击
     */
    private void clicks() {
        //跳转消息编辑
        RxView.clicks(btn_right).subscribe(o -> {
//            Intent intentNotice = new Intent(getActivity(), NoticeEditActivity.class);
//            startActivity(intentNotice);
            if (!isShow) {
                viewBottom.setVisibility(View.VISIBLE);
                isShow = true;
            } else {
                viewBottom.setVisibility(View.GONE);
                isShow = false;
            }

            for (NoticeItemModel noticeItemModel : noticeItemModels) {
                noticeItemModel.setShowCheck(isShow);
                noticeItemModel.setSelect(false);
            }
            noticeItemAdapter.notifyDataSetChanged();
        });

        //已读
        RxView.clicks(tvReading).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            noticeChooseReadingItemModels.clear();
            JSONArray jsonArray = new JSONArray();
            for (NoticeItemModel itemModel : noticeItemModels) {
                if (itemModel.isSelect()) {
                    jsonArray.put(itemModel.getNoticeId());
                }
            }

            if (jsonArray.length() == 0) {
                ToastUtils.show("请先选择需要读取的消息！");
                return;
            }

            readData(jsonArray);
        });

        //置顶
        RxView.clicks(tvTop).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            JSONArray jsonArray = new JSONArray();
            boolean isAllTop = true;
            for (NoticeItemModel itemModel : noticeItemModels) {
                if (itemModel.isSelect()) {
                    jsonArray.put(itemModel.getNoticeId());
                    if (itemModel.getSpecify() != 0) {
                        //有一个不为你0，type传0，反之传1
                        isAllTop = false;
                    }
                }
            }

            if (jsonArray.length() == 0) {
                ToastUtils.show("请先选择需要置顶的消息！");
                return;
            }

            topData(jsonArray, isAllTop);
        });

        //刪除
        RxView.clicks(tvNoticeDelete).throttleFirst(2, TimeUnit.SECONDS).subscribe(o -> {
            JSONArray jsonArray = new JSONArray();
            for (NoticeItemModel itemModel : noticeItemModels) {
                if (itemModel.isSelect()) {
                    jsonArray.put(itemModel.getNoticeId());
                }
            }

            if (jsonArray.length() == 0) {
                ToastUtils.show("请先选择需要删除的消息！");
                return;
            }

            if (null == deleteNoticeDialog) {
                deleteNoticeDialog = new DeleteNoticeDialog(getActivity(), R.style.dialogFullStyle, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.tvSubmit) {
                            deleteMessage(jsonArray);

                            deleteNoticeDialog.dismiss();
                        }
                    }
                });
            }

            deleteNoticeDialog.show();
        });


    }

    /**
     * 已读
     */
    private void readData(JSONArray jsonArray) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("UserId", userId);
        maps.put("token", token);
        maps.put("sysNoticesList", jsonArray);

        showPd();
        presenter.userNoticeRead(maps);
    }

    /**
     * 置顶
     */
    private void topData(JSONArray jsonArray, boolean isAllTop) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("UserId", userId);
        maps.put("token", token);
        maps.put("sysNoticesList", jsonArray);

        if (isAllTop) {
            maps.put("type", 1);
        } else {
            maps.put("type", 0);
        }

        showPd();
        presenter.userNoticeTop(maps);
    }

    /**
     * 删除消息
     *
     * @param jsonArray
     */
    private void deleteMessage(JSONArray jsonArray) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("UserId", userId);
        maps.put("token", token);
        maps.put("sysNoticesList", jsonArray);
        showPd();
        presenter.userNoticeDelete(maps);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //fragment里使用ButterKnife一定要销毁
        //unbinder.unbind();
    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {
        switch (tag) {
            //消息列表
            case ResponseTag.USER_MESSAGE_LIST:
                List<NoticeItemModel> noticeItemModelList = (List<NoticeItemModel>) model;
                //刷新操作时，先清除之前的数据再添加，防止数据重复
                if (isRefresh) {
                    noticeItemModels.clear();
                }

                noticeItemModels.addAll(noticeItemModelList);

                //刷新列表
                noticeItemAdapter.notifyDataSetChanged();
                break;

            //已读/置顶/删除
            case ResponseTag.USER_MESSAGE_READ:
            case ResponseTag.USER_MESSAGE_TOP:
            case ResponseTag.USER_MESSAGE_DELETE:
                ToastUtils.show(msg == null ? "成功" : msg);
                hidePd();
                //重新请求，刷新列表
                viewBottom.setVisibility(View.GONE);
                isShow = false;

                loadData();
                break;

            default:
                break;
        }
        srlRefresh.finishRefresh();
    }

    @Override
    public void onError(int errcode, int tag, String message) {
        ToastUtils.show(message == null ? "获取消息失败" : message);
        srlRefresh.finishRefresh();
        hidePd();
    }
}